package fenyu.personblob.bean.observe.logobserve;

import fenyu.personblob.bean.databean.logs.LogBean;
import fenyu.personblob.bean.observe.Observe;

import java.io.File;
import java.io.FileWriter;

/**
 * create at 2018/12/22 7:28
 *
 * @author 纷羽 <gzj0078@gmail.com>
 */
public class LogSaveToFileObserve implements Observe {

    private FileWriter fileWritter = null;
    private File file = new File("logger.out");

    public LogSaveToFileObserve() {
        try {
            if (!file.exists()) {
                if (file.getParentFile() != null && !file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
            System.out.println("Log file create at " + file.getAbsoluteFile().toString());
            fileWritter = new FileWriter(file, true);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public void update(Object... args) {
        LogBean logBean = (LogBean) args[0];
        if (fileWritter != null && logBean.getType() >= 2) {
            try {
                fileWritter.append(logBean.toString() + "\r\n");
                fileWritter.flush();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}
